import os
from datetime import datetime

from flask import request
from werkzeug.security import generate_password_hash, check_password_hash
import shutil

from src.init.init_path import DEFAULT_AVATAR_PATH
from src.model.UserModel import UserModel
from src.api.https import SUCCESS, FAIL
from src.init.init_db import db

items = ["name", "email", "phone", "qq", "avatar", "info", "role"]
USERNAME = 1
UID = 2


class UserTool:
    def __init__(self):
        self.username = None
        self.role = 0
        self.url = None

    def init(self, username: str, password: str, name: str) -> None:
        """
        :param username: 用户账号
        :param password: 密码
        :param name: 用户名
        """
        print(len(generate_password_hash(password, salt_length=8)))
        user = UserModel(username=username, name=name,
                         password=generate_password_hash(password, salt_length=8), avatar="imgresource"+DEFAULT_AVATAR_PATH)
        db.session.add(user)
        db.session.commit()

    def check(self, username: str, password: str, name: str):
        """
        :param username: 用户账号
        :param password: 用户密码
        :param name: 用户名
        """
        if len(username) == 0 or len(password) == 0 or len(name) == 0:
            return "用户账号、用户密码和用户昵称不能为空"
        elif len(name) > 16:
            return "用户昵称过长"
        elif len(username) > 100:
            return "请输入正确的账号"
        elif len(password) < 8 or len(password) > 16:
            return "密码请保持在8-16位"
        elif UserModel.query.filter_by(username=username).first() is not None:
            return "当前账户已经被注册"

        return SUCCESS

    def check_password(self, username: str, password: str, type: int):
        """
        :param username: 用户账号 / uid
        :param password: 用户密码
        :param type: 选择使用username(1) / uid(2)
        """
        if type == USERNAME:
            user = UserModel.query.filter_by(username=username).first()
        else:
            user = UserModel.query.filter_by(uid=username).first()

        if user is None or not check_password_hash(user.password, password):
            return "用户名或密码错误"

        return user

    def delete(self, md_path: str) -> int:

        return SUCCESS

    def update(self, info: dict, uid: int) -> bool:
        """
        :param info: 更新信息字典
        :param uid: 用户id
        对用户信息进行更新
        """
        user = UserModel.query.filter_by(uid=uid).first()
        if not user:
            print("用户未找到")
            return False  # 如果用户不存在/uid过期，返回 False

        for item in items:
            if item in info and info[item] is not None and info[item] != getattr(user, item):
                print(f'item = {item}, info = {info[item]} ')
                setattr(user, item, info[item])
        db.session.commit()
        return True

    def list(self, uid: int) -> dict:
        """
        :param uid: 用户id
        根据用户id查找用户信息
        """
        user = UserModel.query.filter_by(uid=uid).first()
        if not user:
            return None

        info = {"uid": uid}
        for item in ["username"] + items:
            info[item] = getattr(user, item)
            if item == "avatar":
                info[item] = "http://" + request.host + "/" + info[item]
            if item == "createtime":
                info[item] = info[item].strftime("%Y年%m月%d日 %H:%M:%S")

        return info
